package com.catcoin.deposit.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.catcoin.deposit.model.Realname;
import com.catcoin.deposit.model.User;
import com.catcoin.deposit.model.UsersBankcards;
import com.catcoin.deposit.result.AppResult;
import com.catcoin.deposit.service.IRealnameService;
import com.catcoin.deposit.service.IUserService;
import com.catcoin.deposit.service.IUsersBankcardsService;
import com.catcoin.deposit.util.BankUtils;
import com.catcoin.deposit.util.IpAddressUtils;
import com.catcoin.deposit.util.MSGUtil;
import com.catcoin.deposit.util.StringUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 实名认证信息表 前端控制器
 * </p>
 *
 * @author 1111
 * @since 2018-09-10
 */
@CrossOrigin
@Controller
public class RealnameController {

    @Autowired
    private  IRealnameService iRealnameService;
    @Autowired
    private IUsersBankcardsService iUsersBankcardsService;
    @Autowired
    private IUserService iUserService;

    /**
     * 个人认证
     * @param userPhone  电话
     * @param accUser    真实姓名
     * @param ID         身份证
     * @param userId     用户id
     * @param accNo      银行卡
     * @param request
     * @return
     */
    @RequestMapping("/quickAuthentication")
    @ResponseBody
    @Transactional
    public AppResult quickAuthentication(String userPhone, String accUser,String ID, Integer userId, String accNo, HttpServletRequest request) {
        try {
            AppResult appResult = iRealnameService.addRealname(userPhone, accUser, ID,  userId,  accNo,  request);
            return appResult;

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AppResult.ERROR("失败", -1);
        }
    }
    /**
     * 添加银行卡
     * @param userPhone  电话
     * @param accUser    真实姓名
     * @param ID         身份证
     * @param userId     用户id
     * @param accNo      银行卡
     * @param request
     * @return
     */
    @RequestMapping("/addBank")
    @ResponseBody
    @Transactional
    public AppResult addBank(String userPhone, String accUser,String ID, Integer userId, String accNo) {
        try {
            if (MSGUtil.isEmpty(userPhone) || MSGUtil.isEmpty(accUser) || MSGUtil.isEmpty(ID) || MSGUtil.isEmpty(accNo)) {
                return AppResult.ERROR("参数不能为空", -1);
            }
            if (userPhone.length() >= 11) {
                if (!StringUtils.checkTel(userPhone)) {
                    return AppResult.ERROR("请填写正确的联系号码", -1);
                }
            }
            //校验身份证填写
            if (!MSGUtil.verify(ID)) {
                return AppResult.ERROR("身份证填写不正确", -1);
            }

            //简单校验银行卡
            if (!MSGUtil.checkBankCard(accNo)) {
                return AppResult.ERROR("卡号输入错误！", -1);
            }

            //过滤填写名字中的特殊字符
            accUser = MSGUtil.StringFilter(accUser);
            if (accUser.equals("")) {
                return AppResult.ERROR("请填写正确姓名", -1);
            }

            //查询该卡号是否添加
            UsersBankcards usersBankcards2 = new UsersBankcards();
            usersBankcards2.setAccNo(accNo);
            usersBankcards2.setDataFlag(1);
            EntityWrapper<UsersBankcards> entityWrapper = new EntityWrapper<UsersBankcards>(usersBankcards2);
            UsersBankcards usersBankcards3 = iUsersBankcardsService.selectOne(entityWrapper);
            if(!MSGUtil.isEmpty(usersBankcards3)){
                return  AppResult.ERROR("该银行卡已经申请",-1);
            }

            //银行卡三要素验证
            JSONObject bankInfoTo3 = BankUtils.getBankInfoTo3(accNo, ID, accUser);
            String status = bankInfoTo3.get("status").toString();
            if (!status.equals("01")) {
                return AppResult.ERROR("银行卡信息有误,请填写正确信息", -1);
            }
            String accArea = (bankInfoTo3.get("area")!=null?bankInfoTo3.get("area").toString():"") + (bankInfoTo3.get("bank")!=null?bankInfoTo3.get("bank").toString():"");
            //-----------------------------------------------------------------------------------------
            UsersBankcards usersBankcards = new UsersBankcards();
            usersBankcards.setUserId(userId);//用户ID
            usersBankcards.setPhone(userPhone);//签约卡的手机号
            usersBankcards.setType(1);//银行卡类型 0充值 支付 1赎回卡
            usersBankcards.setProvinceId(0);//省id
            usersBankcards.setAreaId(0);//区县id
            usersBankcards.setCityId(0);//市id
            usersBankcards.setBankId(0);//银行ID(即开户支行ID)
            usersBankcards.setAccArea(accArea);//开户行
            usersBankcards.setAccNo(accNo);//银行卡号
            usersBankcards.setDataFlag(1);//有效标志
            usersBankcards.setCreateTime(new Date());
            boolean insert = iUsersBankcardsService.insert(usersBankcards);
            if (!insert) {
                return AppResult.ERROR("添加银行卡失败", -1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AppResult.ERROR("失败", -1);
        }
        return AppResult.OK("添加银行卡成功", null);
    }
    /**
     * 解绑银行卡
     * @param bankId  银行卡自增id
     * @param request
     * @return
     */
    @RequestMapping("/relieveBank")
    @ResponseBody
    @Transactional
    public AppResult relieveBank(Integer bankId) {
        try {
            if (MSGUtil.isEmpty(bankId)) {
                return AppResult.ERROR("参数不能为空", -1);
            }

            UsersBankcards usersBankcards = new UsersBankcards();
            usersBankcards.setBankCardId(bankId);
            usersBankcards.setDataFlag(-1);
            boolean b = iUsersBankcardsService.updateById(usersBankcards);
            if(!b){
                return AppResult.ERROR("解除银行卡失败",-1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AppResult.ERROR("失败", -1);
        }
        return AppResult.OK("解除银行卡成功", null);
    }

    /**
     * 获取银行卡列表
     * @param userId  用户id
     * @param request
     * @return
     */
    @RequestMapping("/bankList")
    @ResponseBody
    @Transactional
    public AppResult bankList(Integer userId) {
        try {
            if (MSGUtil.isEmpty(userId)) {
                return AppResult.ERROR("参数不能为空", -1);
            }
            //根据用户名获取银行卡列表
//            EntityWrapper<UsersBankcards> entityWrapper = new EntityWrapper<UsersBankcards>();
//            entityWrapper.where("userId",userId);
//            List<UsersBankcards> usersBankcardsList = iUsersBankcardsService.selectList(entityWrapper);
            List<Map<String,Object>> usersBankcardsList = iUsersBankcardsService.selectBankList(userId);

            return AppResult.OK(usersBankcardsList);

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AppResult.ERROR("失败", -1);
        }
    }
}

